let App = getApp();
const func = require('../../utils/func');

Page({
    data: {
        source: '',
        addressList: [],
        isLoading: true
    },

    onLoad: function(options) {
        let _this = this;
        _this.data.source = options.source ? options.source : _this.data.source;
    },

    onShow: function() {
        let _this = this;
        _this.getAddressList();
    },

    // 监听用户下拉动作
    onPullDownRefresh: function () {
        let _this = this;
        _this.getAddressList();
        wx.stopPullDownRefresh()
    },

    // 获取地址列表
    getAddressList() {
        let _this = this;
        App._requestApi(_this, App.globalData.config.shopAddressListUrl,{}, function(res) {
            let addressList = res.data.list;
            let default_id = res.data.default_id;
            _this.setData({
                addressList,
                isLoading: false,
                default_id
            })
        },function (res) {
            App.showError(res.msg);
        })
    },

    // 编辑地址
    editAddress: function(e) {
        wx.navigateTo({
            url: "./detail?address_id=" + e.currentTarget.dataset.id
        });
    },

    // 移除收货地址
    removeAddress: function(e) {
        let _this = this,
        address_id = e.currentTarget.dataset.id;
        if (address_id) {
        wx.showModal({
            title: "提示",
            content: "您确定要移除当前收货地址吗?",
            success: function(o) {
                if(o.confirm) {
                    App._requestPost(_this,App.globalData.config.shopAddressActionUrl,
                    {'action': 'find_del', addr_id: address_id},
                    function (res) {
                            _this.getAddressList();
                        },
                        function (res) {
                            App.showError(res.msg);
                        }
                    );
                }
            }
        });
        }
    },

    // 选择收货地址并返回到下单页
    selectAddress(e) {
        let _this = this;
        if (_this.data.source && 'goodsBuy' == _this.data.source) {
            let index = e.currentTarget.dataset.index;
            let addr_id = _this.data.addressList[index]['addr_id'] ? _this.data.addressList[index]['addr_id'] : 0;
            let postData = {
                action: 'default',
                addr_id: addr_id,
            };
            App._requestApi(_this, App.globalData.config.shopAddressActionUrl, postData,
                function(res) {
                    wx.navigateBack();
                },
                function(res) {
                    App.showError(res.msg);
                }
            );
        }
    },

    jumpToUrl(e) {
        func.jumpToUrl(e)
    },
});